package part05;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

public class FlinkTableDemo {
    public static void main(String[] args) throws Exception {
        // 1,获取flink stream 执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 2，创建Table执行环境
        EnvironmentSettings settings = EnvironmentSettings.newInstance()
                .useBlinkPlanner()
                .inStreamingMode()
                .build();
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env, settings);

        //3, 获取数据源
        DataStreamSource<Tuple2<String, Integer>> data = env.addSource(new SourceFunction<Tuple2<String, Integer>>() {
            int count = 0;

            @Override
            public void run(SourceContext<Tuple2<String, Integer>> ctx) throws Exception {
                while (true) {
                    ctx.collect(new Tuple2<>("name" + count, count));
                    count++;
                    Thread.sleep(1000);
                }
            }

            @Override
            public void cancel() {

            }
        });

        // 把流式数据做成Table
        Table table = tableEnv.fromDataStream(data, $("name"), $("age"));
        // table 数据查询
        Table name = table.select($("name"));
        Table age = table.select($("age"));
        // table数据装换成流式数据
        DataStream<Tuple2<Boolean, Row>> stream = tableEnv.toRetractStream(name, Row.class);
        DataStream<Tuple2<Boolean, Row>> ageStream = tableEnv.toRetractStream(age, Row.class);
        // 输出数据
        stream.print();
        // 触发执行作业
        env.execute();
    }
}
